package com.songshuai.webapi.common.log;

import com.alibaba.fastjson.JSON;
import com.songshuai.webapi.baseapi.annotations.SysLogger;
import com.songshuai.webapi.baseapi.pojo.SysLog;
import com.songshuai.webapi.baseapi.utils.HttpUtils;
import com.songshuai.webapi.common.mqchannel.OutputSource;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.security.core.context.SecurityContextHolder;

import java.lang.reflect.Method;

public class BaseSysLoggerAspect {


    protected void sentSysLog(JoinPoint joinPoint,SysLog sysLog) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();


        SysLogger sysLogger = method.getAnnotation(SysLogger.class);
        if(sysLogger != null){
            //注解上的描述
            sysLog.setOperation(sysLogger.operation());
            sysLog.setValue(sysLogger.value());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params="";
        for(Object o:args){
            params+=JSON.toJSONString(o);
        }
        if(!StringUtils.isEmpty(params)) {
            sysLog.setParams(params);
        }
        //设置IP地址
        sysLog.setIp(HttpUtils.getIpAddress());
        sysLog.setUri(HttpUtils.getHttpServletRequest().getRequestURI());
        //用户名
        String username = String.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        if(!StringUtils.isEmpty(username)) {
            sysLog.setUsername(username);
        }
    }


}
